import { defineStore } from 'pinia';
import { messageFn } from '../../utils';
import {
  getUserListApi,
  getUsersInfo,
  getInvoiceListApi,
  getAwaitListApi,
  getFinishListApi,
  rushredApi,
  reInvoiceApi,
  invoiceApi,
  listByDetailApi,
  listSendInvoiceApi,
  mergeInvoiceApi,
} from '/@/api/comprehensive/index';
import {
  HomeModel,
  CurrentPageType,
  SearchUserForm,
  CustomerInfo,
  tabsActionType,
} from '/#/store/comprehensive/index';
import { routeKey } from '/#/comprehensive/home';

import { tabsAction } from '/@/views/comprehensive//data/home';
import { useLoading } from '/@/components/Loading';
import { cloneDeep, fill, partial } from 'lodash-es';
import { useTablePage } from '/@/hooks/common/useTablePage';

const [openFullLoading, closeFullLoading] = useLoading({
  tip: '加载中...',
});

export const comprehensiveStore = defineStore({
  id: 'comprehensive-state',
  state: (): HomeModel => ({
    currentComponents: 'HOME',  // 当前主界面 'home' | 'BUSINESS'
    currentStatus: 'AWAIT',  // 是否正在办理中 "AWAIT" | "START" 目前未接入呼号机，暂时无用
    searchForm: {}, // 搜索表单、包扣混合查询和高级查询
    tabsAction: cloneDeep(tabsAction),  // 主页查缴水费、票据打印、业务记录、消息模块配置
    route: 'accountRoute',  // 当前路由
    childrenRoute: '',  // 二级路由
    userList: [], // 查询出来的用户列表
    ckeckList: [], // 选择框选择的用户id
    checkRows: [], // 选择框选择的用户信息
    userInfo: {},  // 选择的第一个用户（主要用于单选账户）
    invoiceId: '', // 发票id
    invoiceTitle: '', // 发票弹框名称
    waicChecked: [],
  }),
  actions: {
    setWaicChecked(data){
      this.waicChecked = data
    },
    // 设置form表单的值
    setSearchForm(searchForm: Partial<SearchUserForm>) {
      this.searchForm = {
        ...searchForm,
      };
    },
    setInvoice(invoiceId: string, invoiceTitle: string) {
      this.invoiceId = invoiceId
      this.invoiceTitle = invoiceTitle
    },
    // 设置form表单的值
    resetSearchForm() {
      this.searchForm = {};
    },
    // 设置选择的用户
    setCkeckList(ckeckList: string[]) {
      this.ckeckList = ckeckList;
      this.userInfo = this.checkRows?.[0] ?? {}
    },
    resetTabsAciton() {
      this.tabsAction = cloneDeep(tabsAction)
    },
    // 路由跳转
    goRoute(route: routeKey, childrenRoute: HomeModel['childrenRoute']) {
      this.route = route
      this.childrenRoute = childrenRoute
    },
    /**
     * @description: 获取用户-标签信息
     */
    async getTagInfoAciton() {
      try {
        const { code, msg, data } = await getUsersInfo(this.ckeckList);
        if (code === 0) {
          // 查缴水费
          this.tabsAction[0].infos[0].value = data.billing_record_vo.unpaid_amout
          this.tabsAction[0].infos[1].value = data.billing_record_vo.unpaid_num
          // 票据打印
          this.tabsAction[1].infos[0].value = data.invoice_record_vo.invoice_amount
          this.tabsAction[1].infos[1].value = data.invoice_record_vo.invoiced
          // 业务记录
          this.tabsAction[2].infos[0].value = data.business_record_vo.processing_num
          this.tabsAction[2].infos[1].value = data.business_record_vo.processed_num
          // 消息记录
          this.tabsAction[3].infos[0].value = data.msg_record_vo.send_success_num
          this.tabsAction[3].infos[1].value = data.msg_record_vo.send_faild_num
        } else {
          messageFn('error', msg);
        }
      } finally {
      }
     
    },
    /**
     * @description: 获取用户列表
     */
    async getUserListAction() {
      openFullLoading();
      const { page_no, page_size, list, searchForm, hanldeQueryPage } = useTablePage({
        api: getUserListApi,
        isPoll: true,
        immediate: false
      })
      page_no.value = 1
      page_size.value = 1000
      searchForm.value = this.searchForm
      await hanldeQueryPage()
      closeFullLoading();
      if (list.value.length === 0) {
        messageFn('error', '用户不存在');
        return Promise.reject('用户不存在') 
      } else {
        this.userList = list.value;
      }
      // try {        
      //   const { code, msg, data } = await getUserListApi(this.searchForm);
      //   if (code === 0) {
      //     if (data.length > 0) {
      //       this.userList = []
      //       this.ckeckList = []
      //       data.forEach((item, i) => {
      //         item.checked = data?.length === 1 ? true : false;
      //       });
      //       this.userList = data;
      //       return true;
      //     } else {
      //       messageFn('error', '用户不存在');
      //       return Promise.reject('用户不存在')
      //     }
      //   } else {
      //     messageFn('error', msg);
      //     return Promise.reject(msg);
      //   }
      // } finally {
      //   closeFullLoading();
      // }
    },
    /**
     * @description: 获取发票下拉
     */
    async getInvoiceListAction() {
      // const { code, msg, data } = await getInvoiceListApi();
      // console.log('data====', data);
      // if (code === 0) {
      //   const invoice = this.businessButton.find((item) => item.text === '票据打印');
      //   const buttons = data.map((item) => {
      //     return {
      //       type: 'button',
      //       title: item.invoice_name,
      //       eventName: 'invoice',
      //       invoice_id: item.invoice_id,
      //       fnName: 'INVOICE',
      //     };
      //   });
      //   invoice!.menuButtons = buttons;
      // } else {
      //   messageFn('error', msg);
      // }
    },
    /**
     * @description: 获取发票下拉
     */
    async getAwaitListAction(params: object): Promise<any> {
      openFullLoading();
      try {
        const { code, msg, data, total } = await getAwaitListApi(params);
        if (code === 0) {
          return {
            data,
            total,
          };
        } else {
          messageFn('error', msg);
        }
      } finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 获取发票下拉
     */
    async getFinishListAction(params: object): Promise<any> {
      openFullLoading();
      try {
        const { code, msg, data, total } = await getFinishListApi(params);
        if (code === 0) {
          return {
            data,
            total,
          };
        } else {
          messageFn('error', msg);
        }
      } finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 发票冲红
     */
    async rushredAction(ids: string[]): Promise<boolean> {
      openFullLoading();
      try {
        const { code, msg } = await rushredApi(ids);
        if (code === 0) {
          messageFn('success', '操作成功');
          return true;
        } else {
          messageFn('error', msg);
          return false;
        }
      } finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 发票重开
     */
    async reInvoiceAction(ids: string[]): Promise<boolean> {
      openFullLoading();
      try {
        const { code, msg } = await reInvoiceApi(ids);
        if (code === 0) {
          messageFn('success', '操作成功');
          return true;
        } else {
          messageFn('error', msg);
          return false;
        }
      } finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 发票重开
     */
    async invoiceAction(params: object): Promise<boolean> {
      openFullLoading();
      try {
        const { code, msg } = await invoiceApi(params);
        if (code === 0) {
          messageFn('success', '操作成功');
          return true;
        } else {
          messageFn('error', msg);
          return false;
        }
      } finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 开票列表
     */
    async listByDetailAciton(params: object): Promise<any> {
      openFullLoading();
      try {
        const { code, msg, data } = await listByDetailApi(params);
        if (code === 0) {
          return {
            data: data.list,
            total: data.total,
          };
        } else {
          messageFn('error', msg);
        }
      }  finally {
        closeFullLoading();
      }
    },
    /**
     * @description: 开票列表
     */
    async listSendInvoiceAction(params: object): Promise<boolean> {
      const { code, msg } = await listSendInvoiceApi(params);
      if (code === 0) {
        messageFn('success', '操作成功');
        return true;
      } else {
        messageFn('error', msg);
        return false;
      }
    },
    /**
     * @description: 批量打印
     */
    async mergeInvoiceAction(params: any): Promise<any> {
      const { code, msg, data } = await mergeInvoiceApi(params);
      if (code === 0) {
        messageFn('success', '操作成功');
        return data;
      } else {
        messageFn('error', msg);
        return false;
      }
    },
  },
});
